﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using Yunchang;
using Yunchang.Scene;

namespace AutoChess
{
    partial class AutoChessManager : FsmControllerBase<AutoChessModeState>
    {
        #region Single
        private static AutoChessManager ins;
        public static AutoChessManager Ins
        {
            get
            {
                if (ins == null)
                {
                    ins = new AutoChessManager();
                }
                return ins;
            }
        }
        
        #endregion

        #region FsmState
        public override void InitState()
        {
            base.InitState();
            allStates[AutoChessModeState.None] = new ACNoneState(AutoChessModeState.None, this);
            allStates[AutoChessModeState.ResLoadState] = new ACResLoadState(AutoChessModeState.ResLoadState, this);//资源加载
            allStates[AutoChessModeState.GameFieldtate] = new ACGameFieldState(AutoChessModeState.GameFieldtate, this);
            allStates[AutoChessModeState.LeaveState] = new ACLeaveState(AutoChessModeState.LeaveState, this);
            allStates[AutoChessModeState.ReconnectState] = new ACReconnectState(AutoChessModeState.ReconnectState, this);
            allStates[AutoChessModeState.ShowFightState] = new ACShowFightState(AutoChessModeState.ShowFightState, this);
        }
        public override void SwitchState(AutoChessModeState stateType)
        {
            if (currentState != null && currentState.GetStateType() == stateType)
                return;

            base.SwitchState(stateType);
            EventManager.TriggerEvent(CommonEvent.ON_AUTOCHESS_STATE_UPDATE, stateType);
        }
        #endregion

        private AutoChessSceneLoadComponent sceneCmpt;
        public AutoChessSceneLoadComponent SceneCmpt
        {
            get { return sceneCmpt; }
        }

        /// <summary>战场表现逻辑 </summary>
        private AutoChessFieldCtr _currentAutoChessField;
        public AutoChessFieldCtr CurrentAutoChessField
        {
            get { return _currentAutoChessField; }
        }
        private bool reconnected = false;//已经重连进去了
        private bool isEnterSceneInit = false;
        private bool enterFightFlag = false; //进入战斗的标识
        public bool EnterFightFlag { get { return enterFightFlag; } set { enterFightFlag = value; } }
        public bool IsEnterSceneInit { get { return isEnterSceneInit; } set { isEnterSceneInit = value; } }
        private float mCachedShadowDistance;
        private bool mIsInit = false;

        public bool IsAutoChessLogicRun
        {
            get { return mIsInit; }
        }
        
        #region Behavour
        public void Tick(float dealteTime)
        {
            UpdateState();
        }

        #region 数据

        public bool IsHaveReconnect()
        {
            return cacheData.reconnectData != null && !reconnected; //有数据 还没进去
        }

        public AutoChessManager()
        {
            cacheData = new AutoChessCacheData();
            InitState();
            SwitchState(AutoChessModeState.None);
        }
        
        //重置战场数据
        public void ResetFieldData()
        {
            if (cacheData != null)
            {
                cacheData.ResetFieldData();
            }
        }
        #endregion

        #region 进入自走棋、退出自走棋
        public void OpenMatchPage()
        {
            SendCSAutoChessInfo();
        }

        /// <summary>
        /// 第一次进入自走棋战场调用的接口(调用该接口的时候 服务器已经同步过一次 玩家数据了)
        /// </summary>
        public void EnterAutoChessField(bool isReconnect = false)
        {
            Debug.Log("<color=red> EnterAutoChessField </color>");
            sceneCmpt = new AutoChessSceneLoadComponent();
            AutoChessManager.Ins.cacheData.SwitchFieldPlayer(StaticData.playerData.playerId);
            RegisterNetInField();
            CreateGameFieldRoot();
            AutoChessFieldViewCtr.Ins.Init(this);
            CameraTools.Instance.HideCamera();
            ClearSceneLogic();
            if (isReconnect)
            {
                SwitchState(AutoChessModeState.ReconnectState);
            }
            else
            {
                SwitchState(AutoChessModeState.ResLoadState);
            }
        }

        /// <summary>
        ///初始化逻辑管理器、生成战场实体、链接渲染器
        /// </summary>
        public void InitGameFieldUnit()
        {
            mIsInit = true;
            GameEvent.GameEventInit();
            _currentAutoChessField = new AutoChessFieldCtr();
            _currentAutoChessField.InitGameField();
            _currentAutoChessField.GenerateFieldUnit();
            _currentAutoChessField.ConnectRenderer(AutoChessFieldViewCtr.Ins);

            mCachedShadowDistance = QualitySettings.shadowDistance;
            QualitySettings.shadowDistance = AutoChessFieldViewCtr.Ins.SceneConfig.shadowDistance;
        }

        public void ClearManager()
        {
            SwitchState(AutoChessModeState.None);

            cacheData.ResetFieldData();

            if (!mIsInit)
                return;
            mIsInit = false;
            CameraTools.Instance.ActiveCamera();
            //AutoChessCamera.Ins.SwitchCamera(false);
            
            SceneUIManager.Instance.SetCamera(SceneUICameraType.ThreeD, CameraTools.Instance.GetCurrentCamera());
            if (_currentAutoChessField != null)
                _currentAutoChessField.Release();//场景逻辑释放，格子 英雄等
            if (AutoChessFieldViewCtr.Ins != null)
            {
                AutoChessFieldViewCtr.Ins.Release();//场景渲染器释放
                GameObject.DestroyImmediate(AutoChessFieldViewCtr.Ins.gameObject);//销毁节点
            }
            AssetManager.Instance.UnloadAsset(GameConst.SceneConfig);

            LoadingPanel.Instance.ClearCloudLoading();

            _currentAutoChessField = null;
            isEnterSceneInit = false;

            QualitySettings.shadowDistance = mCachedShadowDistance;
            //ShadowManager.Instance.BattleToScene();
        }
        //退出战场到场景
        public void ExistGameFieldToScene()
        {
            UnRegisterNetInField();
            ClearManager();
            Resources.UnloadUnusedAssets();
            Yunchang.EventManager.TriggerEvent<string, bool, float>(CommonEvent.ShowLoading, "", false, 3f);
            PageManager.Instance.ClosePage("AutoChessMainPage");
            SceneManager.Instance.RequestBack2PreScene();
        }

        public void CheckGameOverOnEnterState()
        {
            //if (cacheData.ServerDataState == ProtoBuf.Message.AutoChessStateType.AUTO_CHESS_STATE_CLOSED)//返回战场进行游戏结果检测
            //{
            //    ExistFightResult();
            //}
        }
        /// <summary>
        /// 游戏退出
        /// </summary>
        //public void ExistFightResult()
        //{
        //    PageManager.Instance.OpenPage("AutoChessBillingInfoPage");
        //}
        #endregion

        #region 进入战斗、退出战斗

        //从战斗场景切到 自走棋战场
        public void OnLeaveFightToEnterField()
        {
            //SwitchState(AutoChessModeState.FightToFieldState);
            enterFightFlag = false;
            
        }
        public void GeneratePlayerEentity(ACPlayerData playerData )
        {
            _currentAutoChessField.GenerateTargetPlayerEntity(playerData);
        }
        #endregion 

        public void SwitchToPlayer(long playerGuid)
        {
           AutoChessFieldViewCtr.Ins.StartCoroutine(  _currentAutoChessField.SwitchWatchingPlayer(playerGuid) );
        }

        /// <summary>
        /// 创建战场渲染器
        /// </summary>
        private void CreateGameFieldRoot()
        {
            var gameFieldRoot = new GameObject("GameFieldRoot");
            gameFieldRoot.transform.Normalize();
            gameFieldRoot.transform.SetParent(GameMain.Instance.transform);
            gameFieldRoot.AddComponent<AutoChessFieldViewCtr>();
        }
        #endregion

        /// <summary>
        /// 清除现有场景相关逻辑
        /// </summary>
        private void ClearSceneLogic()
        {
            TeamTools.TeamStopMatch();
            CountDown.Instance.BreakCountDown();
            MessageBoxManager.Instance.ClearNormal();
            EventManager.TriggerEvent<bool, bool>(CommonEvent.ON_STOP_TASK_AUTOMATION, true, true);
            SceneManager.Instance.CurrentScene.Destroy();
        }
    }

    public enum AutoChessModeState
    {
        None,//待机状态
        ResLoadState,  //资源进度,玩家进度加载
        GameFieldtate,  //战场状态
        LeaveState,    //结束游戏离开
        ReconnectState, //重新连接
        ShowFightState,//战斗显示状态
    }
}